<?php


namespace app\controller;


use app\job\Capture;
use app\model\MqttCarPushInfo;
use app\model\ViidDevice;
use think\facade\Log;
use think\facade\Queue;
use think\facade\Request;

class Faces extends BackendController{
    protected $model = null;
    public function _initialize()
    {
        //parent::_initialize();
        $this->model = new \app\model\Faces();
    }

    public function compare($id){
        $res=$this->model->compare_by_face_id($id);
    }

    /**
     * 以图搜图
     * @param $photo
     * @param string $start_time
     * @param string $end_time
     */
    public function compare_photo($photo,$start_time='',$end_time=''){
        $res=$this->model->compare_photo($photo,$start_time,$end_time);
        $this->success('比较成功',$res);
    }

    /**
     * 新以图搜图
     * @param $photo
     * @param string $start_time
     * @param string $end_time
     */
    public function compare_photo_feature($photo,$start_time='',$end_time='',$page=1,$limit=10,$score=80){
        Log::info("新以图搜图".$score);
        $res=$this->model->compare_photo_feature($photo,$start_time,$end_time,$page,$limit,$score);
        $this->success('比较成功',$res);
    }

    public function compare_photo_features($photo,$start_time='',$end_time='',$page=1,$limit=10,$score=80){
        $res=$this->model->compare_photo_features($photo,$start_time,$end_time,$page,$limit,$score);
        $this->success('比较成功',$res);
    }

    public function before_del($lists){
        foreach ($lists as $list) {
            $bg_path=$list['file_path'].$list['id'].'_bg.jpg';
            $face_path=$list['file_path'].$list['id'].'_face.jpg';
            if(file_exists($bg_path)){
                unlink($bg_path);
            }
            if(file_exists($face_path)){
                unlink($face_path);
            }
        }

    }

    /**
     * 非1400推送
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function facein(){

        $now_time=date("Y-m-d H:i:s");
        $log_id=md5($now_time).rand(1000,9999);
        Log::info($log_id.'非1400推送》facein 接口被请求');
        $recive= file_get_contents('php://input');
        if(!$recive){
            //swoole接收参数
            $recive=$this->request->getInput();
        }

        // Log::debug($log_id.'非1400推送》face_in：：：'.$recive);
        $get_json=json_decode($recive);
        $body=$get_json->body;
        $faces=[];
        if(isset($body->face)){
            Log::debug($log_id.'非1400推送》臻识S1M'.$get_json->reco_id);
            //臻识S1Mface_in
            if($body->face[0]->confidence<=50)
            {
                //Log::error('facein score 低于 50 返回');
                Log::warning($log_id.'非1400推送》图片评分小于50:'.$body->face[0]->confidence);
                $this->error('face_bad');
            }
            if($get_json->cmd!='face_snapshot'){
                Log::error($log_id.'非1400推送》推送类型不正确:'.$get_json->cmd);
                $this->error('face_request');
            }
            $serialno=$body->serialno;

            $device=ViidDevice::where('ape_id','=',$serialno)->find();
            if(!$device){
                Log::warning($log_id.'非1400推送》设备表中没有该设备:'.$serialno);
                $this->error('no_device');
            }
            //Log::info(json_encode($device->toArray()));
            $face['DeviceID']=$device['device_id'];
            $face['FaceID']=$body->face[0]->face_id;
            $face['SourceID']=$face['DeviceID'].($get_json->reco_id?'':$get_json->reco_id);

            $images[0]['Data']=$body->picture[0]->data;
            $images[0]['ImageID']=$face['DeviceID'].$get_json->reco_id.'0';
            $images[1]['Data']=$body->snapshot->data;
            $images[1]['ImageID']=$face['DeviceID'].$get_json->reco_id.'1';
            $face['SubImageList']['SubImageInfoObject'][0]=$images[1];
            $face['SubImageList']['SubImageInfoObject'][1]=$images[0];
            $faces['FaceListObject']['FaceObject'][]=$face;
        }elseif (isset($body->results)){
            Log::debug($log_id.'非1400推送》臻识S1M');
            //臻识S5Lface_in
            //只有一张图，先扔掉
            //只有一张图，先扔掉Log::info(' facein 接口被请求');

            if(count($get_json->image_data)==1){
                Log::error($log_id.'非1400推送》只有一张图，先扔掉');
                $this->error('face_bad');
            }
            if($body->results[0]->face_prop->score<=50)
            {
                Log::warning($log_id.'非1400推送》图片评分小于50:'.$body->results[0]->face_prop->score);
                //Log::error('facein score 低于 50 返回');
                $this->error('face_bad');
            }
            if($body->type!='common_alarm_result'){
                Log::error($log_id.'非1400推送》推送类型不正确:'.$body->type);
                $this->error('face_request');
            }
            $serialno=$body->device_info->sn;
            $device=ViidDevice::where('ape_id','=',$serialno)->find();
            if(!$device){
                Log::warning($log_id.'非1400推送》设备表中没有该设备:'.$serialno);
                $this->error('no_device');
            }
            //Log::info(json_encode($device->toArray()));
            $reco_id=$body->results[0]->event_uuid;
            $face['DeviceID']=$device['device_id'];
            $face['FaceID']=$body->results[0]->face_prop->face_id;
            $face['SourceID']=$face['DeviceID'].$reco_id;

            $images[0]['Data']=$get_json->image_data[0]->image_str;
            $images[0]['ImageID']=$face['DeviceID'].$reco_id.'0';
            $images[1]['Data']=$get_json->image_data[1]->image_str;
            $images[1]['ImageID']=$face['DeviceID'].$reco_id.'1';
            $face['SubImageList']['SubImageInfoObject'][0]=$images[0];
            $face['SubImageList']['SubImageInfoObject'][1]=$images[1];
            $faces['FaceListObject']['FaceObject'][]=$face;
        }
        if($faces){
            $content=json_encode($faces);
            $job_data = [];
            $job_data["ts"] = time();
            $job_data["bizid"] = uniqid();
            $job_data["params"] =$content;
            $job_data["log_id"]=$log_id;
            $is_pushed=Queue::push(Capture::class,$job_data,'http_list');
        }
        //Log::info('content:::'.$content);
        /*$_face=new \app\model\Faces();
        $_face->saev_face($content,$log_id);*/
        /*$job_data = [];
        $job_data["ts"] = time();
        $job_data["bizid"] = uniqid();
        $job_data["params"] =$content;*/
        //$is_pushed=Queue::push(Capture::class,$job_data,'capture_list');
        $this->success();

    }

    public function carin(){
        $recive= file_get_contents('php://input');
        //Log::debug("臻识车辆推送：：：".$recive);
        $recive=json_decode($recive,true);
        $_car=new MqttCarPushInfo();
        $_car->save_push($recive);
    }

    public function carin_hik(){
        $recive= file_get_contents('php://input');
        //Log::debug("hik平台车辆推送：：：".$recive);
        // $recive=json_decode($recive,true);
        // $_car=new MqttCarPushInfo();
        // $_car->save_push($recive);
    }
    public function heartbeat(){
        $recive= file_get_contents('php://input');
        Log::info("推送心跳：：：".$recive);
        $User_Identify=Request::header();
        Log::info("推送心跳1：：：".json_encode($User_Identify));
        $this->success();
    }

    /**
     * 查询$day天内未出现的人
     * @param $day
     * @return void
     */
    public function user_lost($day=30,$page=1,$limit=10){
        $lists=$this->model->user_lost($day,$page,$limit);
        $this->success('获取成功',$lists);

    }

    public function stranger($all_day=30,$absent_day=20,$page=1,$limit=10){
        $lists=$this->model->stranger($all_day,$absent_day,$page,$limit);
        $this->success('获取成功',$lists);
    }

    public function index_group($device_id,$time=8) {
        $_face=new \app\model\Faces();
        $end_time=time();
        $start_time=strtotime("- $time hours");
        $lists=$_face->where('device_id',$device_id)
            ->whereBetweenTime('create_time',$start_time,$end_time)
            ->field('count(*),day(create_time) days,hour(create_time) hours')
            ->group('day(create_time),hour(create_time)')
            ->select();
        Log::info("xxxxxsql1:".$_face->getLastSql());
        foreach ($lists as $list){
            $map[$list['days'].'_'.$list['hours']]=$list['count(*)'];
        }
        for ($i=$time;$i>0;$i--){
            $now_time=strtotime("- $i hours");
            $now_time_str=date('d',$now_time).'_'.date('H',$now_time);
            if(!isset($map[$now_time_str])){
                $map[$now_time_str]=0;
            }
        }
        ksort($map);
        $result[]=array_keys($map);
        $result[]=array_values($map);
        $this->success('获取成功',$result);
    }




}